/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.wordplat.quickstart.slice;

import com.wordplat.ikvstockchart.InteractiveKLineLayout;
import com.wordplat.ikvstockchart.InteractiveKLineView;
import com.wordplat.ikvstockchart.KLineHandler;
import com.wordplat.ikvstockchart.compat.PerformenceAnalyser;
import com.wordplat.ikvstockchart.entry.Entry;
import com.wordplat.ikvstockchart.entry.EntrySet;
import com.wordplat.ikvstockchart.entry.SizeColor;
import com.wordplat.ikvstockchart.entry.StockDataTest;
import com.wordplat.ikvstockchart.render.KLineRender;
import com.wordplat.quickstart.ResourceTable;
import com.wordplat.quickstart.base.BaseAbilitySlice;
import com.wordplat.quickstart.utils.ToastViewDialog;
import com.wordplat.quickstart.wight.PullLayout.pulllistview.HeadDefaultComponent;
import com.wordplat.quickstart.wight.PullLayout.pulllistview.IRefresh;
import com.wordplat.quickstart.wight.PullLayout.pulllistview.OnRefreshComponent;
import com.wordplat.quickstart.wight.PullLayout.pulllistview.RefreshComponent;

import ohos.aafwk.content.Intent;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.*;
import ohos.agp.utils.RectFloat;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.multimodalinput.event.TouchEvent;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * With_Pull_To_Refresh_Example_Slice
 *
 * @since 2021-04-30
 */
public class With_Pull_To_Refresh_Example_Slice extends BaseAbilitySlice {
    private RefreshComponent refreshComponent;
    private InteractiveKLineLayout kLineLayout;
    private Text MA_Text;
    private Text StockIndex_Text;
    private Text Volume_Text;
    private Image Left_Loading_Image;
    private Image Right_Loading_Image;
    private RadioContainer But_Group;
    private RadioButton MACD_But;
    private RadioButton RSI_But;
    private RadioButton KDJ_But;
    private RadioButton BOLL_But;

    private EntrySet entrySet;
    private int loadStartPos = 5500;
    private int loadEndPos = 6000;
    private final int loadCount = 100;

    /**
     * 动画效果 mAnimator
     */
    private AnimatorProperty mAnimator;
    /**
     * viewOnTouchInterface
     */
    public InteractiveKLineView.ViewOnTouchInterface viewOnTouchInterface;

    /**
     * 定义回调方法
     *
     * @param onRefreshComponent
     */
    private OnRefreshComponent onRefreshComponent;

    /**
     * setOnRefresh
     *
     * @param onRefreshComponent
     */
    public void setOnRefresh(OnRefreshComponent onRefreshComponent) {
        this.onRefreshComponent = onRefreshComponent;
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_slice_with_pull_to_refresh);
        initViews();
        loadKLineData();
    }

    private void initViews() {
        refreshComponent = (RefreshComponent) findComponentById(ResourceTable.Id_pullRefreshComponent);
        kLineLayout = (InteractiveKLineLayout) findComponentById(ResourceTable.Id_kLineLayout);
        MA_Text = (Text) findComponentById(ResourceTable.Id_MA_Text);
        StockIndex_Text = (Text) findComponentById(ResourceTable.Id_StockIndex_Text);
        Volume_Text = (Text) findComponentById(ResourceTable.Id_Volume_Text);
        Left_Loading_Image = (Image) findComponentById(ResourceTable.Id_Left_Loading_Image);
        Right_Loading_Image = (Image) findComponentById(ResourceTable.Id_Right_Loading_Image);

        But_Group = (RadioContainer) findComponentById(ResourceTable.Id_But_Group);
        MACD_But = (RadioButton) findComponentById(ResourceTable.Id_MACD_But);
        RSI_But = (RadioButton) findComponentById(ResourceTable.Id_RSI_But);
        KDJ_But = (RadioButton) findComponentById(ResourceTable.Id_KDJ_But);
        BOLL_But = (RadioButton) findComponentById(ResourceTable.Id_BOLL_But);

        refreshComponent.setKLineView(kLineLayout.getKLineView());
        /**
         * 设置头部刷新样式,可自定义样式
         */
        HeadDefaultComponent headDefaultComponent = new HeadDefaultComponent(this);
        /**
         * 添加样式到头部
         */
        refreshComponent.setHeadComponent(headDefaultComponent);

        /**
         * 设置刷新回调
         */
        refreshComponent.setRefreshListener(new IRefresh.RefreshListener() {
            @Override
            public void onRefresh() {
                TaskDispatcher globalTaskDispatcher = getMainTaskDispatcher();
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        // 数据更新完  结束掉刷新
                        refreshComponent.refreshFinish();
                    }
                };
                globalTaskDispatcher.delayDispatch(runnable,2000);
            }

            @Override
            public boolean enableRefresh() {
                return false;
            }
        });
        kLineLayout.setClick(But_Group, MACD_But, RSI_But, KDJ_But, BOLL_But);
        kLineLayout.setKLineHandler(new KLineHandler() {
            @Override
            public void onHighlight(Entry entry, int entryIndex, float x, float y) {
                String maString = null;
                String volumeString = null;
                String str = null;
                maString = String.format(getString(ResourceTable.String_ma_highlight),
                        entry.getMa5(),
                        entry.getMa10(),
                        entry.getMa20());
                volumeString = String.format(getString(ResourceTable.String_volume_highlight),
                        entry.getVolumeMa5(),
                        entry.getVolumeMa10());

                if (kLineLayout.isShownMACD()) {
                    str = String.format(getString(ResourceTable.String_macd_highlight),
                            entry.getDiff(),
                            entry.getDea(),
                            entry.getMacd());
                } else if (kLineLayout.isShownKDJ()) {
                    str = String.format(getString(ResourceTable.String_kdj_highlight),
                            entry.getK(),
                            entry.getD(),
                            entry.getJ());
                } else if (kLineLayout.isShownRSI()) {

                    str = String.format(getString(ResourceTable.String_rsi_highlight),
                            entry.getRsi1(),
                            entry.getRsi2(),
                            entry.getRsi3());
                } else if (kLineLayout.isShownBOLL()) {
                    str = String.format(getString(ResourceTable.String_boll_highlight),
                            entry.getMb(),
                            entry.getUp(),
                            entry.getDn());
                }


                MA_Text.setText(maString);
                Volume_Text.setText(volumeString);
                StockIndex_Text.setText(str);
            }

            @Override
            public void onCancelHighlight() {
                String maString = getString(ResourceTable.String_ma_normal);
                MA_Text.setText(maString);
                Volume_Text.setText("");

                String stockIndexString = "";
                if (kLineLayout.isShownMACD()) {
                    stockIndexString = getString(ResourceTable.String_macd_normal);
                } else if (kLineLayout.isShownKDJ()) {
                    stockIndexString = getString(ResourceTable.String_kdj_normal);
                } else if (kLineLayout.isShownRSI()) {
                    stockIndexString = getString(ResourceTable.String_rsi_normal);
                } else if (kLineLayout.isShownBOLL()) {
                    stockIndexString = getString(ResourceTable.String_boll_normal);
                }
                StockIndex_Text.setText(stockIndexString);
            }

            @Override
            public void onLeftRefresh() {
                Left_Loading_Image.setVisibility(Component.VISIBLE);
                mAnimator = Left_Loading_Image.createAnimatorProperty();
                mAnimator.setDuration(1500).rotate(360).setLoopedCount(AnimatorProperty.INFINITE)
                        .setTarget(Left_Loading_Image).start();
                TaskDispatcher globalTaskDispatcher = getMainTaskDispatcher();
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        Left_Loading_Image.setVisibility(Component.HIDE);

                        List<Entry> entries = insertEntries();

                        kLineLayout.getKLineView().getRender().getEntrySet().insertFirst(entries);
                        kLineLayout.getKLineView().notifyDataSetChanged();
                        kLineLayout.getKLineView().refreshComplete(entries.size() > 0);

                        if (entries.size() == 0) {
                            ToastViewDialog.toast(getContext(), "已经到达最左边了");
                        }
                    }
                };
                globalTaskDispatcher.delayDispatch(runnable, 1000);
            }

            @Override
            public void onRightRefresh() {
                Right_Loading_Image.setVisibility(Component.VISIBLE);
                mAnimator = Left_Loading_Image.createAnimatorProperty();
                mAnimator.setDuration(1500).rotate(360).setLoopedCount(AnimatorProperty.INFINITE)
                        .setTarget(Left_Loading_Image).start();
                TaskDispatcher globalTaskDispatcher = getMainTaskDispatcher();
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        Right_Loading_Image.setVisibility(Component.HIDE);

                        List<Entry> entries = addEntries();

                        kLineLayout.getKLineView().getRender().getEntrySet().addEntries(entries);
                        kLineLayout.getKLineView().notifyDataSetChanged();
                        kLineLayout.getKLineView().refreshComplete(entries.size() > 0);

                        if (entries.size() == 0) {
                            ToastViewDialog.toast(getContext(), "已经到达最右边了");
                        }
                    }
                };
                globalTaskDispatcher.delayDispatch(runnable, 1000);
            }

            @Override
            public void onSingleTap(TouchEvent e, float x, float y) {
                final KLineRender kLineRender = (KLineRender) kLineLayout.getKLineView().getRender();
                if (contains(kLineRender.getKLineRect(), x, y)) {
                    ToastViewDialog.toast(getContext(), "single tab [" + x + ", " + y + "]");
                }
            }

            @Override
            public void onDoubleTap(TouchEvent e, float x, float y) {
                final KLineRender kLineRender = (KLineRender) kLineLayout.getKLineView().getRender();
                if (contains(kLineRender.getKLineRect(), x, y)) {
                    kLineRender.zoomIn(x, y);
                }
            }
        });
    }

    private void loadKLineData() {
        TaskDispatcher globalTaskDispatcher = getMainTaskDispatcher();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                PerformenceAnalyser.getInstance().addWatcher();

                String kLineData = "";
                ResourceManager resourceManager = getContext().getResourceManager();
                RawFileEntry rawFileEntry = resourceManager.getRawFileEntry("resources/rawfile/kline1.txt");
                Resource resource = null;
                try {
                    resource = rawFileEntry.openRawFile();
                    byte[] buffer = new byte[resource.available()];
                    resource.read(buffer);
                    kLineData = new String(buffer, StandardCharsets.UTF_8);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                entrySet = StockDataTest.parseKLineData(kLineData);
                entrySet.computeStockIndex();
                kLineLayout.getKLineView().setEntrySet(loadFirst());
                kLineLayout.getKLineView().notifyDataSetChanged();
            }
        };
        globalTaskDispatcher.asyncDispatch(runnable);
    }

    private EntrySet loadFirst() {
        EntrySet set = new EntrySet();

        for (int i = loadStartPos; i < loadEndPos; i++) {
            set.addEntry(entrySet.getEntryList().get(i));
        }
        return set;
    }

    private List<Entry> addEntries() {
        List<Entry> entries = new ArrayList<>();

        int addCount = 0;
        for (int i = loadEndPos; i < loadEndPos + loadCount && i < entrySet.getEntryList().size(); i++) {
            addCount++;

            entries.add(entrySet.getEntryList().get(i));
        }
        loadEndPos += addCount;

        return entries;
    }

    private List<Entry> insertEntries() {
        List<Entry> entries = new ArrayList<>();

        int insertCount = 0;
        for (int i = loadStartPos; i > loadStartPos - loadCount && i > -1; i--) {
            insertCount++;

            entries.add(entrySet.getEntryList().get(i));
        }
        loadStartPos -= insertCount;

        return entries;
    }

    private boolean contains(RectFloat rectFloat, float x, float y) {
        return rectFloat.left < rectFloat.right && rectFloat.top < rectFloat.bottom
                && x >= rectFloat.left && x < rectFloat.right && y >= rectFloat.top && y < rectFloat.bottom;
    }
}
